<?php
class Response
{
    const JSON = 'application/json';
    const HTML = 'text/html';
    const JAVASCRIPT = 'text/javascript';
    const JS   = 'text/javascript';
    const TEXT = 'text/plain';
    const XML  = 'text/xml';

    static public $response_type = null;

    static public function success($data = [], $exit = true, $content_type = Response::JSON)
    {
        self::$response_type = Response::JSON;

        if (is_object($data))
            $data = get_object_vars($data);
        else if (! is_array($data))
            $data = $data;

        $response['result'] = true;
        $response['data'] = $data;

        if (isset($_REQUEST['jsonp_callback'])) {
            echo $_REQUEST['jsonp_callback'] . '(' . htmlspecialchars(json_encode(gbk2utf8($response)), ENT_NOQUOTES) . ')';
        } else {
            if ($content_type!==null) {
                header("Content-type: " . $content_type);
            }

            echo htmlspecialchars(json_encode($response), ENT_NOQUOTES);
        }

        if ($exit) {
            exit;
        }
    }

    static public function fail($data = [], $exit = true, $content_type = Response::JSON)
    {
        self::$response_type = Response::JSON;

        if (is_object($data))
            $data = get_object_vars($data);
        else if (! is_array($data))
            $data = $data;

        $response['result'] = false;
        $response['data'] = $data;

        if (isset($_REQUEST['jsonp_callback'])) {
            echo $_REQUEST['jsonp_callback'] . '(' . htmlspecialchars(json_encode(gbk2utf8($response)), ENT_NOQUOTES) . ')';
        } else {
            if ($content_type!==null) {
                header("Content-type: " . $content_type);
            }
            echo htmlspecialchars(json_encode($response), ENT_NOQUOTES);
        }

        if ($exit) {
            exit;
        }
    }
}

?>